﻿import { SettingsService } from '@delon/theme';
import { Component, Injector, Output, EventEmitter, ElementRef, OnInit, ViewChild } from '@angular/core';
import {FormBuilder,FormControl,FormGroup,Validators} from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
import { WeixinSettingEditDto } from "@shared/model/weixinSettingdto";
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { AppComponentBase } from "@shared/component-base/app-component-base";


@Component({
  templateUrl: './weixinsetting.component.html'
})
export class WeixinSettingComponent extends AppComponentBase implements OnInit{
  isVisible = false;
  active: boolean = false;
  validateForm: FormGroup;
  weixinSetting: WeixinSettingEditDto = null;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  constructor(
    private injector: Injector,
    private httpClient: HttpClient,
    private fb: FormBuilder,
    public msg: NzMessageService
  ) {
    super(injector);
  }

  showModal(): void {
    this.weixinSetting = new WeixinSettingEditDto();
    this.httpClient.get("weixinsetting/info").subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.weixinSetting.init(result.data);
        }
      });

    this.validateForm.reset();
    this.active = true;
  }

  handleSave(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) {
      return;
    }

    this.httpClient.post("weixinsetting/edit", this.weixinSetting.toJSON()).subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.msg.create("success", "保存成功！");
        }
      });
  }

  handleCancel(): void {
    this.active = false;
    this.isVisible = false;
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }


  ngOnInit(): void {
    this.validateForm = this.fb.group({
      id: [null],
      appId: [null],
      appSecret: [null],
      appUrl: [null],
      appToken: [null],
      appEncodingAESKey: [null],
      miniProgramAppId: [null],
      miniProgramSecret: [null],
      merchantId: [null],
    });

    this.active = true;
    this.validateForm.reset();
    this.showModal();
  }
}
